<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
    <div class="task-container" v-show="showTask">
      <div v-for="(task, index) in todoList" :key="index">
        <Icon class="icon" :icon="task.icon" /><span>{{ task.msg }}</span>
      </div>
    </div>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref, reactive } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema, taskList } from './table.data';
  import { Icon } from '/@/components/Icon';

  import { addTable, updateTable, genTable, genMenu, genCrud } from '/@/api/free/table';
  export default defineComponent({
    name: 'TableModal',
    components: { BasicModal, BasicForm, Icon },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);
      let showTask = ref(false);
      const todoList = reactive(taskList);

      const [registerForm, { resetFields, setFieldsValue, updateSchema, validate }] = useForm({
        labelWidth: 100,
        schemas: formSchema,
        showActionButtonGroup: false,
      });

      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        resetFields();
        setModalProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;

        if (unref(isUpdate)) {
          // 不允许修改表名
          updateSchema({ field: 'tableName', componentProps: { disabled: true } });
          setFieldsValue({
            ...data.record,
          });
        } else {
          updateSchema({ field: 'tableName', componentProps: { disabled: false } });
        }
      });

      const getTitle = computed(() => (!unref(isUpdate) ? '新增表' : '编辑表'));
      function changeTask(index: number, finish: boolean) {
        todoList[index].setStatus(finish ? 'finish' : 'error');

        const notFinish = todoList.findIndex((task) => task.getStatus() !== 'finish');
        if (notFinish == -1) {
          console.log(taskList);
          showTask.value = false;
          // todoList.
          closeModal();
        }
      }

      async function handleSubmit() {
        try {
          const values = await validate();
          setModalProps({ confirmLoading: true });
          if (unref(isUpdate)) {
            await updateTable(values).then((data) => {
              console.log(data);
              closeModal();
              emit('success');
            });
          } else {
            await addTable(values).then(async () => {
              emit('success');
              showTask.value = true;
              await genTable(values)
                .then(() => changeTask(0, true))
                .catch(() => changeTask(0, false));
              await genCrud(values)
                .then(() => changeTask(1, true))
                .catch(() => changeTask(1, false));
              await genMenu(values)
                .then(() => changeTask(2, true))
                .catch(() => changeTask(2, false));
            });
          }
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }

      return { registerModal, todoList, registerForm, getTitle, handleSubmit, showTask };
    },
  });
</script>
<style lang="less" scoped>
  .task-container {
    padding: 20px 0 0 100px;
    line-height: 45px;
    color: @primary-color;

    .icon {
      margin-right: 10px;
    }
  }
</style>
